Tomáš Pospíšek's Notizblock

Pascal's "WITH" in Ruby

For a long time I wondered why Ruby didn't have Pascal's "WITH" construct. It's completely trivial to implent though...

def with object, &block
  object.instance_eval(&block)
end

Now instead of needing to name your object all the time:

object = Object.new
object.foo
object.bazbar

You can instead just do:

with object do
  foo
  bazbar
end

Oh the simple wonders of metaprogramming :-o :-)))

Tomáš Pospíšek, 2011-03-08

Articles